package com.ghxxzx.dagl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ghxxzx.dagl.annotation.LocalLock;
import com.ghxxzx.dagl.entity.*;
import com.ghxxzx.dagl.exceptions.JyException;
import com.ghxxzx.dagl.mapper.*;
import com.ghxxzx.dagl.service.DalrService;
import com.ghxxzx.dagl.utils.PoiUtils;
import com.ghxxzx.dagl.utils.WsFlag;
import com.ghxxzx.dagl.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.ngram.NGramTokenizer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;
import java.security.Key;
import java.util.*;

@Api(value = "档案录入")
@RestController
@RequestMapping("/dalr/api")
public class DalrController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private DalrService dalrService;
    @Autowired
    private DaxxMapper daxxMapper;
    @Autowired
    private ClxxMapper clxxMapper;
    @Autowired
    private DaxxWsMapper daxxWsMapper;
    @Autowired
    private WsFlag wsFlag;
    @Autowired
    private DaLxGlController glController;
    @Autowired
    private DalxMapper dalxMapper;
    @Autowired
    private DaxxRgMapper daxxRgMapper;
    @Autowired
    private DaxxWsRgMapper daxxWsRgMapper;
    @Autowired
    private ClxxRgMapper clxxRgMapper;
    @Autowired
    private GryfKjMapper gryfKjMapper;
    @Autowired
    private GryfKjRgMapper gryfKjRgMapper;
    @Value("${lucene.index}")
    private String indexPath;

    @ApiOperation(value = "科技信息Excel导入", notes = "查询")
    @RequestMapping(value = "kjxxExcleDr")
    public ResultEntity kjxxExcleDr(MultipartFile file,Integer typeId,HttpSession httpSession) {
        Directory d = null;
        IndexWriterConfig conf = null;
        IndexWriter indexWriter = null;

        try {
            d = FSDirectory.open(new File(indexPath));
            conf = new IndexWriterConfig(Version.LATEST, getAnalyzer());
            indexWriter = new IndexWriter(d, conf);
            User user = (User) httpSession.getAttribute("user");
            Workbook hssfWorkbook = PoiUtils.getWorkBookByFile(file);
            Sheet sheetAt = hssfWorkbook.getSheetAt(0);
            int rows = sheetAt.getPhysicalNumberOfRows();
            ArrayList<DaxxRg> daxxes = new ArrayList<>();
            Dalx dalx = dalxMapper.selectById(typeId);
            for (int i = 1; i < rows; i++) {
                Row row = sheetAt.getRow(i);
                String dabh = PoiUtils.getCellValue(row.getCell(5));
                if (StringUtils.isEmpty(dabh)){
                    break;
                }
                String lb = PoiUtils.getCellValue(row.getCell(1));
                String sxh = PoiUtils.getCellValue(row.getCell(2));
                String dtslbh = PoiUtils.getCellValue(row.getCell(3));
                String yhh = PoiUtils.getCellValue(row.getCell(4));
                String jsdw = PoiUtils.getCellValue(row.getCell(6));
                String xmmc = PoiUtils.getCellValue(row.getCell(7));
                String jswz = PoiUtils.getCellValue(row.getCell(8));
                String jsxmxzyjsj = PoiUtils.getCellValue(row.getCell(9));
                String xzxmmc = PoiUtils.getCellValue(row.getCell(10));
                String xzydmj = PoiUtils.getCellValue(row.getCell(11));
                String jsydghxkzsj = PoiUtils.getCellValue(row.getCell(12));
                String ghxmmc = PoiUtils.getCellValue(row.getCell(13));
                String ghydmj = PoiUtils.getCellValue(row.getCell(14));
                String jsgcghxkzjsj = PoiUtils.getCellValue(row.getCell(15));
                String gcxmmc = PoiUtils.getCellValue(row.getCell(16));
                String gcjsgm = PoiUtils.getCellValue(row.getCell(17));
                String jsgcjgghyshgsj = PoiUtils.getCellValue(row.getCell(18));
                String gcjgxmmc = PoiUtils.getCellValue(row.getCell(19));
                String gcjgjsgm = PoiUtils.getCellValue(row.getCell(20));
                String jsgcsgxkzsj = PoiUtils.getCellValue(row.getCell(21));
                String jsgcsgxkzbh = PoiUtils.getCellValue(row.getCell(22));
                String sggcmc = PoiUtils.getCellValue(row.getCell(23));
                String sgjsgm = PoiUtils.getCellValue(row.getCell(24));
                String qt = PoiUtils.getCellValue(row.getCell(25));
                String xmfatgsj = PoiUtils.getCellValue(row.getCell(26));
                String ys = PoiUtils.getCellValue(row.getCell(27));
                String daccwz = PoiUtils.getCellValue(row.getCell(28));
                String clj = PoiUtils.getCellValue(row.getCell(29));
                String zly = PoiUtils.getCellValue(row.getCell(30));
                String zlsj = PoiUtils.getCellValue(row.getCell(31));
                String year = PoiUtils.getCellValue(row.getCell(32));
                if (dabh.length()<10){
                    throw new JyException((i+1)+"行，档案编号规范");
                }
//                String code = getCode(dabh);
                if (StringUtils.isEmpty(xmmc)){
                    throw new JyException((i+1)+"行，项目名称为空");
                }
                String bz = PoiUtils.getCellValue(row.getCell(1));
//                QueryWrapper<Dalx> dalxQueryWrapper = new QueryWrapper<>();
//                dalxQueryWrapper.eq("code", code);
//                Dalx dalx = dalxMapper.selectOne(dalxQueryWrapper);
//                if (dalx==null){
//                    throw new JyException((i+1)+"行，档案类型不存在");
//                }
                Daxx daxx = daxxMapper.findByDabh(dabh);
                if (daxx!=null){
                    throw new JyException((i+1)+"行，档案编号已录入");
                }
                DaxxRg byDabh = daxxRgMapper.findByDabh(dabh);
                if (byDabh != null) {
                    throw new JyException((i+1)+"行，该档案编号已入馆");
                }
                if (year==null){
                    year="0";
                }
                try {
                    daxxes.add(new DaxxRg(dalx.getId(),sxh,dabh,yhh,xmmc,jsdw,jswz,dtslbh,daccwz,Integer.parseInt(year),dalx.getDalxName(),bz,qt,
                            xmfatgsj,ys,clj,zly,jsxmxzyjsj,xzxmmc,xzydmj,jsydghxkzsj,ghxmmc,ghydmj,jsgcghxkzjsj,gcxmmc,gcjsgm,jsgcjgghyshgsj,gcjgxmmc,gcjgjsgm,jsgcsgxkzsj,jsgcsgxkzbh,sggcmc,sgjsgm,zlsj,new Date(),user.getName()));
                } catch (JyException e) {
                    log.error(e.getMess(), e);
                    return ResultEntity.error(e.getMess());
                }catch (DuplicateKeyException e){
                    log.error(e.getMessage(), e);
                    return ResultEntity.error("档案编号已重复");
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return ResultEntity.error("请上传正确的Excel模板文件及数据（第"+(i+1)+"行)");
                }

            }
            HashMap<String, Integer> hashMap = new HashMap<>();
            Daxx daxx1 = new Daxx();
            Field[] fields = daxx1.getClass().getDeclaredFields();
            for (Field field : fields) {
                String name = field.getName();
                hashMap.put(name,0);
            }
            for (DaxxRg daxx : daxxes) {
                Class daxxClass = daxx.getClass();
                for (String fieldName : hashMap.keySet()) {
                    String s = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
                    Object invoke = daxxClass.getMethod(s).invoke(daxx);
                    String s1 = invoke == null ? null : invoke.toString();
                    if ((s1==null?0:s1.length())>hashMap.get(fieldName)){
                        hashMap.put(fieldName,s1.length());
                    }
                }
            }
            System.out.println(hashMap);

            return dalrService.kjxxExcleDr(daxxes,user,d,conf,indexWriter);
        } catch (JyException e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMessage(), e);
            return ResultEntity.error("请上传正确的Excel模板文件及数据");
        }finally {
            if (indexWriter!=null){
                try {
                    indexWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    @ApiOperation(value = "科技信息个人用房Excel导入", notes = "查询")
    @RequestMapping(value = "kjxxGryfExcleDr")
    public ResultEntity kjxxGryfExcleDr(MultipartFile file,Integer typeId,HttpSession httpSession) {
        Directory d = null;
        IndexWriterConfig conf = null;
        IndexWriter indexWriter = null;
        try {
            d = FSDirectory.open(new File(indexPath));
            conf = new IndexWriterConfig(Version.LATEST, getAnalyzer());
            indexWriter = new IndexWriter(d, conf);
            User user = (User) httpSession.getAttribute("user");
            Workbook hssfWorkbook = PoiUtils.getWorkBookByFile(file);
            Sheet sheetAt = hssfWorkbook.getSheetAt(0);
            int rows = sheetAt.getPhysicalNumberOfRows();
            ArrayList<GryfKj> gryfKjs = new ArrayList<>();
            Dalx dalx = dalxMapper.selectById(typeId);
            for (int i = 1; i < rows; i++) {
                Row row = sheetAt.getRow(i);
                String dabh = PoiUtils.getCellValue(row.getCell(1));
                if (StringUtils.isEmpty(dabh)){
                    break;
                }
                String xh = PoiUtils.getCellValue(row.getCell(0));
                String bsc = PoiUtils.getCellValue(row.getCell(2));
                String jwh = PoiUtils.getCellValue(row.getCell(3));
                String sqr = PoiUtils.getCellValue(row.getCell(4));
                String sqsx = PoiUtils.getCellValue(row.getCell(5));
                String spsj = PoiUtils.getCellValue(row.getCell(6));
                String sqcl = PoiUtils.getCellValue(row.getCell(7));
                String bz = PoiUtils.getCellValue(row.getCell(8));
                String qsym = PoiUtils.getCellValue(row.getCell(9));
                String zzym = PoiUtils.getCellValue(row.getCell(10));
                String zys = PoiUtils.getCellValue(row.getCell(11));
                String zhh = PoiUtils.getCellValue(row.getCell(12));
                String year = PoiUtils.getCellValue(row.getCell(13));
                if (dabh.trim().length()<10){
                    throw new JyException((i+1)+"行，档案编号规范");
                }
//                String code = getCode(dabh);
//                QueryWrapper<Dalx> dalxQueryWrapper = new QueryWrapper<>();
//                dalxQueryWrapper.eq("code", code);
//                Dalx dalx = dalxMapper.selectOne(dalxQueryWrapper);
//                if (dalx==null){
//                    throw new JyException((i+1)+"行，档案类型不存在");
//                }
                GryfKj gryfKj = gryfKjMapper.findByDabh(dabh);
                if (gryfKj!=null){
                    throw new JyException((i+1)+"行，档案编号已录入");
                }
                GryfKjRg byDabh = gryfKjRgMapper.findByDabh(dabh);
                if (byDabh != null) {
                    throw new JyException((i+1)+"行，该档案编号已入馆");
                }
                if (year==null){
                    year="0";
                }
                try {
                    gryfKjs.add(new GryfKj(dabh,bsc,jwh,sqr,sqsx,spsj,sqcl,bz,qsym,zzym,zys,zhh,year,dalx.getId(),dalx.getDalxName(),new Date(),user.getName()));
                } catch (JyException e) {
                    log.error(e.getMess(), e);
                    return ResultEntity.error(e.getMess());
                }catch (DuplicateKeyException e){
                    log.error(e.getMessage(), e);
                    return ResultEntity.error("档案编号已重复");
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return ResultEntity.error("请上传正确的Excel模板文件及数据（第"+(i+1)+"行)");
                }

            }

            HashMap<String, Integer> hashMap = new HashMap<>();
            GryfKj gryfKj = new GryfKj();
            Field[] fields = gryfKj.getClass().getDeclaredFields();
            for (Field field : fields) {
                String name = field.getName();
                hashMap.put(name,0);
            }
            for (GryfKj gryfKj1 : gryfKjs) {
                Class daxxClass = gryfKj1.getClass();
                for (String fieldName : hashMap.keySet()) {
                    String s = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
                    Object invoke = daxxClass.getMethod(s).invoke(gryfKj1);
                    String s1 = invoke == null ? null : invoke.toString();
                    if ((s1==null?0:s1.length())>hashMap.get(fieldName)){
                        hashMap.put(fieldName,s1.length());
                    }
                }
            }
            System.out.println(hashMap);
            return dalrService.kjxxGryfExcleDr(gryfKjs,user,d,conf,indexWriter);
        } catch (JyException e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMessage(), e);
            return ResultEntity.error("请上传正确的Excel模板文件及数据");
        }finally {
            if (indexWriter != null) {
                try {
                    indexWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public Analyzer getAnalyzer() {
        Analyzer analyzer = new Analyzer() {
            @Override
            protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
                Tokenizer source = new NGramTokenizer(reader, 1, 255);
                TokenStream filter = new StopFilter(source, new CharArraySet(0, false));
                return new TokenStreamComponents(source, filter);
            }
        };
        return analyzer;
    }
    @ApiOperation(value = "文书信息Excel导入", notes = "查询")
    @RequestMapping(value = "wsxxExcleDr")
    public ResultEntity wsxxExcleDr(MultipartFile file,Integer typeId,HttpSession httpSession) {
        Directory d = null;
        IndexWriterConfig conf = null;
        IndexWriter indexWriter = null;
        try {
            d = FSDirectory.open(new File(indexPath));
            conf = new IndexWriterConfig(Version.LATEST, getAnalyzer());
            indexWriter = new IndexWriter(d, conf);
            User user = (User) httpSession.getAttribute("user");
            Workbook hssfWorkbook = PoiUtils.getWorkBookByFile(file);
            Sheet sheetAt = hssfWorkbook.getSheetAt(0);
            int rows = sheetAt.getPhysicalNumberOfRows();
            ArrayList<DaxxWsRg> daxxWs = new ArrayList<>();
            Dalx dalx = dalxMapper.selectById(typeId);
            for (int i = 1; i < rows; i++) {
                Row row = sheetAt.getRow(i);
                String dabh = PoiUtils.getCellValue(row.getCell(1));
                if (StringUtils.isEmpty(dabh)){
                    break;
                }
                String dwmc = PoiUtils.getCellValue(row.getCell(3));
                String wjmc = PoiUtils.getCellValue(row.getCell(4));
                if (StringUtils.isEmpty(wjmc)){
                    throw new JyException((i+1)+"行，文件名称为空");
                }
                String sj = PoiUtils.getCellValue(row.getCell(5));
                String wh = PoiUtils.getCellValue(row.getCell(6));
                String yh = PoiUtils.getCellValue(row.getCell(7));
                String ys = PoiUtils.getCellValue(row.getCell(8));
                String bz = PoiUtils.getCellValue(row.getCell(9));
                String zhh = PoiUtils.getCellValue(row.getCell(10));
                String nf = PoiUtils.getCellValue(row.getCell(11));
                if (dabh.length()<10){
                    throw new JyException((i+1)+"行，档案编号不规范");
                }
//                String code = getCode(dabh);
//                QueryWrapper<Dalx> dalxQueryWrapper = new QueryWrapper<>();
//                dalxQueryWrapper.eq("code", code);
//                Dalx dalx = dalxMapper.selectOne(dalxQueryWrapper);
//                if (dalx==null){
//                    throw new JyException((i+1)+"行，档案类型不存在");
//                }
                DaxxWs byDabh = daxxWsMapper.findByDabh(dabh.trim());
                if (byDabh!=null){
                    throw new JyException((i+1)+"行，档案编号已录入");
                }
                DaxxWsRg daxxWsRg = daxxWsRgMapper.findByDabh(dabh);
                if (daxxWsRg != null) {
                    throw new JyException((i+1)+"行，该档案编号已入馆");
                }

                if (nf == null || nf.isEmpty()) {
                    nf = "0";
                }
                try {
                    daxxWs.add(new DaxxWsRg(dabh, wh, yh, ys, zhh, dalx.getDalxName(), dalx.getId(), dwmc, wjmc, sj, Integer.parseInt(nf), bz,new Date(),user.getName()));
                } catch (JyException e) {
                    log.error(e.getMess(), e);
                    return ResultEntity.error(e.getMess());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return ResultEntity.error("请上传正确的Excel模板文件及数据（第"+(i+1)+"行)");
                }
            }
            HashMap<String, Integer> hashMap = new HashMap<>();
            DaxxWsRg daxxWsRg = new DaxxWsRg();
            Field[] fields = daxxWsRg.getClass().getDeclaredFields();
            for (Field field : fields) {
                String name = field.getName();
                hashMap.put(name,0);
            }
            for (DaxxWsRg daxxWsRg1 : daxxWs) {
                Class daxxClass = daxxWsRg1.getClass();
                for (String fieldName : hashMap.keySet()) {
                    String s = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
                    Object invoke = daxxClass.getMethod(s).invoke(daxxWsRg1);
                    String s1 = invoke == null ? null : invoke.toString();
                    if ((s1==null?0:s1.length())>hashMap.get(fieldName)){
                        hashMap.put(fieldName,s1.length());
                    }
                }
            }
            System.out.println(hashMap);

            return dalrService.wsxxExcleDr(daxxWs,user,d,conf,indexWriter);
        } catch (JyException e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        }catch (DuplicateKeyException e){
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMessage(), e);
            return ResultEntity.error("档案编号已重复");
        }catch (Exception e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMessage(), e);
            return ResultEntity.error("请上传正确的Excel模板文件及数据");
        } finally {
            if (indexWriter != null) {
                try {
                    indexWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "材料信息Excel导入", notes = "查询")
    @RequestMapping(value = "clxxExcleDr")
    public ResultEntity clxxExcleDr(MultipartFile file,Integer typeId) {
        Directory d = null;
        IndexWriterConfig conf = null;
        IndexWriter indexWriter = null;
        try {
            d = FSDirectory.open(new File(indexPath));
            conf = new IndexWriterConfig(Version.LATEST, getAnalyzer());
            indexWriter = new IndexWriter(d, conf);
            Workbook hssfWorkbook = PoiUtils.getWorkBookByFile(file);
            Sheet sheetAt = hssfWorkbook.getSheetAt(0);
            int rows = sheetAt.getPhysicalNumberOfRows();
            ArrayList<ClxxRg> list = new ArrayList<>();
            Dalx dalx = dalxMapper.selectById(typeId);
            for (int i = 1; i < rows; i++) {
                Row row = sheetAt.getRow(i);
                String dabh = PoiUtils.getCellValue(row.getCell(1));
                if (StringUtils.isEmpty(dabh)){
                    break;
                }
                String clxh = PoiUtils.getCellValue(row.getCell(2));
                if (clxh.length()!=3){
                    throw new JyException((i+1)+"行，文件序号规范");
                }
                String clmc = PoiUtils.getCellValue(row.getCell(3));
                if (StringUtils.isEmpty(clmc)){
                    throw new JyException((i+1)+"行，材料名称为空");
                }
                String qsym = PoiUtils.getCellValue(row.getCell(5));
                String zzym = PoiUtils.getCellValue(row.getCell(6));
                String fs = PoiUtils.getCellValue(row.getCell(4));
                String bz = PoiUtils.getCellValue(row.getCell(7));
                String wh = PoiUtils.getCellValue(row.getCell(9));
                String ys = PoiUtils.getCellValue(row.getCell(10));
                String slsj = PoiUtils.getCellValue(row.getCell(8));
                if (dabh.length()<10){
                    throw new JyException((i+1)+"行，档案编号规范");
                }
//                String code = getCode(dabh);
//                QueryWrapper<Dalx> dalxQueryWrapper = new QueryWrapper<>();
//                dalxQueryWrapper.eq("code", code);
//                Dalx dalx = dalxMapper.selectOne(dalxQueryWrapper);
                if (dalx==null){
                    throw new JyException((i+1)+"行，档案类型不存在");
                }
                if (fs == null || fs.isEmpty()) {
                    fs = "0";
                }
                if (ys == null || ys.isEmpty()) {
                    ys = "0";
                }
                Daxx daxx = daxxMapper.findByDabh(dabh);
                DaxxWs daxxWs = daxxWsMapper.findByDabh(dabh);
                GryfKj gryfKj = gryfKjMapper.findByDabh(dabh);
                if (daxx == null && daxxWs == null && gryfKj==null) {
                    throw new JyException((i+1)+"行，该档案编号档案信息没有录入");
                }
//                DaxxRg daxxRg = daxxRgMapper.findByDabh(dabh);
//                DaxxWsRg daxxWsRg = daxxWsRgMapper.findByDabh(dabh);
//                if (daxxWsRg == null && daxxRg == null) {
//                    throw new JyException((i+1)+"行，该档案编号档案信息没有录入");
//                }
                QueryWrapper<ClxxRg> wrapper = new QueryWrapper<>();
                wrapper.eq("dabh",dabh);
                wrapper.eq("wjxh", clxh);
                wrapper.eq("clmc", clmc);
                ClxxRg selectOne = clxxRgMapper.selectOne(wrapper);
                if (selectOne != null) {
                    throw new JyException((i+1)+"行，该材料信息已录入");
                }
                QueryWrapper<Clxx> clxxQueryWrapper = new QueryWrapper<>();
                clxxQueryWrapper.eq("dabh",dabh);
                clxxQueryWrapper.eq("wjxh", clxh);
                clxxQueryWrapper.eq("clmc", clmc);
                Clxx clxx2= clxxMapper.selectOne(clxxQueryWrapper);
                if (clxx2 != null) {
                    throw new JyException("该材料信息已入馆");
                }
                try {
//                    if (clmc==null||clxh==null||dabh==null){
//                        throw new JyException("材料名称，文件序号，档案编号都不能为空");
//                    }
                    list.add(new ClxxRg(dabh, clxh, clmc, Integer.parseInt(fs), qsym, zzym, Integer.parseInt(ys), bz, null, dalx.getId(), dalx.getDalxName(), wh, slsj));
                } catch (JyException e) {
                    log.error(e.getMess(), e);
                    return ResultEntity.error(e.getMess());
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    return ResultEntity.error("请上传正确的Excel模板文件及数据（第"+((i+1))+"行)");
                }

            }
            HashMap<String, Integer> hashMap = new HashMap<>();
            Clxx clxx1 = new Clxx();
            Field[] fields = clxx1.getClass().getDeclaredFields();
            for (Field field : fields) {
                String name = field.getName();
                hashMap.put(name,0);
            }
            for (ClxxRg clxxRg : list) {
                Class clxxRgClass = clxxRg.getClass();
                for (String fieldName : hashMap.keySet()) {
                    String s = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
                    Object invoke = clxxRgClass.getMethod(s).invoke(clxxRg);
                    String s1 = invoke == null ? null : invoke.toString();
                    if ((s1==null?0:s1.length())>hashMap.get(fieldName)){
                        hashMap.put(fieldName,s1.length());
                    }
                }
            }
            System.out.println(hashMap);
            return dalrService.clxxExcleDr(list,d,conf,indexWriter);
        } catch (JyException e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
           if (indexWriter!=null){
               try {
                   indexWriter.rollback();
               } catch (IOException e1) {
                   e1.printStackTrace();
               }
           }
            log.error(e.getMessage(), e);
            return ResultEntity.error("请上传正确的Excel模板文件及数据");
        } finally {
            if (indexWriter != null) {
                try {
                    indexWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "檔案一览表查询", notes = "查询")
    @RequestMapping(value = "queryDayilb")
    public ResultEntity queryDayilb() {
        try {
            return dalrService.queryDayilb();
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "檔案一览表Ws查询", notes = "查询")
    @RequestMapping(value = "queryDayilbWs")
    public ResultEntity queryDayilbWs() {
        try {
            return dalrService.queryDayilbWs();
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    /**
     * 档案目录查询
     * desc降序Asc升序 默认降序
     * @param keyword
     * @param dalx
     * @param sort
     * @param pageSize
     * @param pageNum
     * @return
     */
    @ApiOperation(value = "檔案查询", notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "查询条件项目名称", required = false, paramType = "query", dataType = "keyword"),
            @ApiImplicitParam(name = "dalx", value = "查询条件档案类型", required = false, paramType = "query", dataType = "dalx"),
            @ApiImplicitParam(name = "sort", value = "降序或者升序", required = false, paramType = "query", dataType = "sort"),
            @ApiImplicitParam(name = "pageSize", value = "查询每页显示条数", required = true, paramType = "query", dataType = "pageSize"),
            @ApiImplicitParam(name = "pageNum", value = "查询当前页", required = true, paramType = "query", dataType = "pageNum")
    })
    @RequestMapping(value = "queryDaxx")
    public ResultEntity queryDaxx(String keyword, Integer dalx,String sort, Integer pageSize, Integer pageNum,String year) {
        try {
            return dalrService.queryDaxx(keyword, dalx,sort, pageSize, pageNum,year);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @RequestMapping(value = "queryDaxxNf")
    public ResultEntity queryDaxxNf(String keyword, Integer dalx) {
        try {
            return dalrService.queryDaxxNf(keyword, dalx);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "档案信息补入", notes = "添加")
    @RequestMapping(value = "dabr")
    public ResultEntity dabr(@RequestBody Daxx daxx, HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
             return dalrService.dabr(daxx,user);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @ApiOperation(value = "档案信息更新", notes = "更新")
    @RequestMapping(value = "updateda")
    public ResultEntity updateda(@RequestBody DaxxRg daxxRg) {
        try {
            return dalrService.updateda(daxxRg);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //=删除科技
    @ApiOperation(value = "档案信息刪除", notes = "删除")
    @RequestMapping(value = "deleteda")
    public ResultEntity deleteda(String dabh) {
        try {
            return dalrService.deleteda(dabh);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //直接删除
    @ApiOperation(value = "档案删除", notes = "删除")
    @RequestMapping(value = "deletedaRg")
    public ResultEntity deletedaRg(String dabh) {
        try {
            return dalrService.deletedaRg(dabh);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //待接入
    @ApiOperation(value = "查询待入馆", notes = "查询")
    @RequestMapping(value = "queryDRg")
    public ResultEntity queryDRg(String sort, PageQuery pageQuery, HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            return dalrService.queryDRg(user,sort,pageQuery);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //待接入
    @ApiOperation(value = "查询待审核", notes = "查询")
    @RequestMapping(value = "queryDSh")
    public ResultEntity queryDSh(String sort,PageQuery pageQuery,HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            return dalrService.queryDSh(user,sort,pageQuery);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @ApiOperation(value = "查询待审核数", notes = "查询")
    @RequestMapping(value = "queryDShCount")
    public ResultEntity queryDShCount(HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            return dalrService.queryDShCount(user);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //待接入
    @ApiOperation(value = "查询回收站", notes = "查询")
    @RequestMapping(value = "queryHsz")
    public ResultEntity queryHsz(String sort,PageQuery pageQuery,HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            return dalrService.queryHsz(user,sort,pageQuery);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //待接入
    @ApiOperation(value = "查询入馆中的档案信息", notes = "查询")
    @RequestMapping(value = "queryRgDaxx")
    public ResultEntity queryRgDaxx(String dabh) {
        try {
            return dalrService.queryRgDaxx(dabh);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    //断点   继续修改

    //待写
    @ApiOperation(value = "档案信息更新文书", notes = "更新")
    @RequestMapping(value = "updatedaWs")
    public ResultEntity updatedaWs(@RequestBody DaxxWsRg daxxWsRg) {
        try {
            return dalrService.updatedaWs(daxxWsRg);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //待写
    @ApiOperation(value = "档案信息刪除文书", notes = "更新")
    @RequestMapping(value = "deletedaWs")
    public ResultEntity deletedaWs(Integer id) {
        try {
            return dalrService.deletedaWs(id);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    //待写
    @ApiOperation(value = "档案信息补入文书", notes = "添加")
    @RequestMapping(value = "dabrWs")
    public ResultEntity dabrWs(@RequestBody DaxxWs daxxWs,HttpSession httpSession) {
        try {
            User user = (User) httpSession.getAttribute("user");
            return dalrService.dabrWs(daxxWs,user);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "档案材料是否存在", notes = "添加")
    @RequestMapping(value = "getFlagClxx")
    public ResultEntity getFlagClxx(String clname, String lb, String dabh, String wjxh) {
        try {
            return dalrService.getFlagClxx(clname, lb, dabh, wjxh);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    //待接入
    @ApiOperation(value = "根据档案号查询材料", notes = "查询")
    @RequestMapping(value = "queryDabhClxx")
    public ResultEntity queryDabhClxx(String dabh) {
        try {
            dabh = dabh.trim();
            return dalrService.queryDabhClxx(dabh);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    //待接入
//    @ApiOperation(value = "上传多档案材料", notes = "添加")
//    @RequestMapping(value = "uploadWsCls")
//    public ResultEntity uploadWsCls(MultipartFile[] files, String clname, String lb, String dabh, String wjxh) {
//        try {
//            return dalrService.uploadWsCls(files, clname, lb, dabh, wjxh);
//        } catch (JyException e) {
//            log.error(e.getMess(), e);
//            return ResultEntity.error(e.getMess());
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return ResultEntity.error("未知异常");
//        }
//    }
//
//    //待写
//    @ApiOperation(value = "上传多档案材料", notes = "添加")
//    @RequestMapping(value = "uploadWsCl")
//    public ResultEntity uploadWsCl(MultipartFile file, String lb, String dabh) {
//        try {
//            return dalrService.uploadWsCl(file, lb, dabh);
//        } catch (JyException e) {
//            log.error(e.getMess(), e);
//            return ResultEntity.error(e.getMess());
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return ResultEntity.error("未知异常");
//        }
//    }
    @LocalLock(key ="clbr:arg[0]")
    @ApiOperation(value = "材料信息补入", notes = "添加")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "dajy",value = "档案借阅",required = true,paramType = "query",dataType = "dajy"),
//            @ApiImplicitParam(name = "shrId",value = "审核人Id",required = true,paramType = "query",dataType = "shrId")
//    })
    @RequestMapping(value = "clbr")
    public ResultEntity clbr(@RequestBody Clxx clxx) {
        try {
            return dalrService.clbr(clxx);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @ApiOperation(value = "材料信息更新", notes = "更新")
    @RequestMapping(value = "updatecl")
    public ResultEntity updatecl(@RequestBody ClxxRg clxxRg) {
        try {
            if (clxxRg.getClmc()==null||clxxRg.getWjxh()==null||clxxRg.getDabh()==null){
                throw new JyException("材料名称，文件序号，档案编号都不能为空");
            }
            return dalrService.updatecl(clxxRg);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @ApiOperation(value = "材料信息回显", notes = "查询")
    @RequestMapping(value = "querycl")
    public ResultEntity querycl(Integer id) {
        try {
            return dalrService.querycl(id);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @ApiOperation(value = "材料信息删除", notes = "添加")
    @RequestMapping(value = "deletecl")
    public ResultEntity deletecl(Integer id) {
        try {
            return dalrService.deletecl(id);
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping(value = "dasf")
    public ResultEntity dasf(String dabh) {
        try {
//            String code = getCode(dabh);
//            Integer integer = dalxMapper.findByCode(code);
            Integer integer = wsFlag.getTypeId(dabh);
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            Integer flag = hashMap.get(integer);
            if (flag==1){
                QueryWrapper<Daxx> wrapper = new QueryWrapper<>();
                wrapper.eq("dabh", dabh);
                Daxx daxx = daxxMapper.selectOne(wrapper);
                DaxxRg byDabh = daxxRgMapper.findByDabh(dabh);
                if (byDabh != null||daxx!=null) {
                    return ResultEntity.error("已重复");
                }else {
                    return ResultEntity.ok("未重复");
                }
            }else if (flag==2){
                GryfKj byDabh = gryfKjMapper.findByDabh(dabh);
                GryfKjRg gryfKjRg = gryfKjRgMapper.findByDabh(dabh);
                if (byDabh != null||gryfKjRg!=null) {
                    return ResultEntity.error("已重复");
                }else {
                    return ResultEntity.ok("未重复");
                }
            }else if (flag==3){
                DaxxWs daxxWs = daxxWsMapper.findByDabh(dabh);
                DaxxWsRg byDabh = daxxWsRgMapper.findByDabh(dabh);
                if (byDabh != null||daxxWs!=null) {
                    return ResultEntity.error("已重复");
                }else {
                    return ResultEntity.ok("未重复");
                }
            }
            return ResultEntity.error("类型不存在");
        }  catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知类型");
        }
    }

    @RequestMapping(value = "findDaByDabh")
    public ResultEntity findDaByDabh(String dabh, Integer tyepId) {
        Map<String, Object> result = new HashMap<>();
        try {
            HashMap<Integer, Integer> hashMap = wsFlag.getDalxFlag();
            Integer lx = hashMap.get(tyepId);
            if (lx==3) {
                QueryWrapper<DaxxWs> daxxWsQueryWrapper = new QueryWrapper<>();
                daxxWsQueryWrapper.eq("dabh", dabh);
                DaxxWs daxxWs = daxxWsMapper.selectOne(daxxWsQueryWrapper);
                result.put("da", daxxWs);
                List<Clxx> clxxes = clxxMapper.selectByDabh(dabh);
                List<LxNode> nodeList = new ArrayList<>();
                for (Clxx clxx : clxxes) {
                    LxNode lxNode = new LxNode();
                    lxNode.setId(clxx.getId() + "");
                    lxNode.setText(clxx.getWjxh()+clxx.getClmc());
                    lxNode.setNodes(new ArrayList<>());
                    nodeList.add(lxNode);
                }
                result.put("cl", nodeList);
            } else if (lx==1){
                QueryWrapper<Daxx> wrapper = new QueryWrapper<>();
                wrapper.eq("dabh", dabh);
                Daxx daxx = daxxMapper.selectOne(wrapper);
                result.put("da", daxx);
                List<Clxx> clxxes = clxxMapper.selectByDabh(dabh);
                List<LxNode> nodeList = new ArrayList<>();
                for (Clxx clxx : clxxes) {
                    LxNode lxNode = new LxNode();
                    lxNode.setId(clxx.getId() + "");
                    lxNode.setText(clxx.getWjxh()+clxx.getClmc());
                    lxNode.setNodes(new ArrayList<>());
                    nodeList.add(lxNode);
                }
                result.put("cl", nodeList);
            }else if (lx==2){
                QueryWrapper<GryfKj> wrapper = new QueryWrapper<>();
                wrapper.eq("dabh", dabh);
                GryfKj gryfKj = gryfKjMapper.selectOne(wrapper);
                result.put("da", gryfKj);
                List<LxNode> nodeList = new ArrayList<>();
                result.put("cl", nodeList);
            }
            return ResultEntity.ok(result);
        }  catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping(value = "cldasf")
    public ResultEntity cldasf(String dabh) {
        try {
            QueryWrapper<Clxx> wrapper = new QueryWrapper<>();
            wrapper.eq("dabh", dabh);
            Clxx clxx = clxxMapper.selectOne(wrapper);
            if (clxx == null) {
                return ResultEntity.ok("未重复");
            } else {
                return ResultEntity.error("已重复");
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @RequestMapping(value = "getClxx")
    public ResultEntity getClxx(Integer id) {
        try {
            Clxx clxx = clxxMapper.selectById(id);
            return ResultEntity.ok(clxx);
        }  catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @RequestMapping(value = "queryDaxxBydabh")
    public ResultEntity queryDaxxBydabh(String dabh){
        try {
            Daxx daxx = daxxMapper.findByDabh(dabh);
            if (daxx==null){
                daxx=new Daxx();
            }
            return ResultEntity.ok(daxx);
        }  catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }

    @ApiOperation(value = "入馆提交审核", notes = "添加")
    @RequestMapping(value = "submitRg")
    public ResultEntity submitRg(Integer id,Integer userId) {
        try {
            return dalrService.submitRg(id,userId);
        }  catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        }
    }
    @ApiOperation(value = "入馆审核", notes = "添加")
    @RequestMapping(value = "rgaudit")
    public ResultEntity rgaudit(Integer id,String rgyj,Integer flag) {
        Directory d = null;
        IndexWriterConfig conf = null;
        IndexWriter indexWriter = null;
        try {
            d = FSDirectory.open(new File(indexPath));
            conf = new IndexWriterConfig(Version.LATEST, getAnalyzer());
            indexWriter = new IndexWriter(d, conf);
            return dalrService.rgaudit(id,rgyj,flag,d,conf,indexWriter);
        }  catch (JyException e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        } catch (Exception e) {
            if (indexWriter!=null){
                try {
                    indexWriter.rollback();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        } finally {
            if (indexWriter != null) {
                try {
                    indexWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
